import md5 from '../md5.js';
let ajaxTimes = 0;
let userInfo = {};
let loginOk = false;
let openid = "";
let role = [];
let isIntercept = false; // 是否已弹出未登录框
let whiteParameter = ["loginZm"]; // 接口白名单
let yhcard = "";
let usermch = ""


const METHOD = {
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE'
}
class Request {
  _header = {
    sessionid: null,
    'content-type': 'application/json'
  }
  // _baseUrl = ""
  // _baseUrlFile  = ""
  // _baseUrlupload  = "" 

  interceptors = []

  constructor() {
    const session_key = wx.getStorageSync('session_key')
    if (session_key !== "") {
      this._header.sessionid = session_key;
    }
  }
  intercept(res) {
    return this.interceptors
      .filter(f => typeof f === 'function')
      .every(f => f(res))
  }

  request({
    method,
    data
  }) {
    var that = this
    return new Promise((resolve, reject) => {
      /*  if( isIntercept){return resolve({data:{msg:"无权限",code:"9900"}});}
       if( whiteParameter.indexOf( data.parameter ) == -1 && loginOk == false){
           isIntercept = true;
           wx.showModal({
               title: '提示',
               content: '获取详细信息需要获取微信用户信息，是否前往登录',
               success: function(res) {
                   isIntercept = false;
                   if (res.confirm) {
                       that.getMyUser();
                   } else if (res.cancel) {
                       wx.reLaunch({url:"/pages/index/index"});
                   }
               }
           })
           return resolve({data:{msg:"无权限",code:"9900"}});
       } */
      /* if( isIntercept){return resolve({data:{msg:"无权限",code:"9900"}});} */
      // if( whiteParameter.indexOf( data.parameter ) == -1 && this.userid == undefined){
      //     wx.showModal({
      //         title: '提示',
      //         content: '用户暂未登录，请先登录。',
      //         success: function(res) {
      //             isIntercept = false;
      //             wx.reLaunch({url:"/pages/login/login"});
      //         }
      //     })
      // }

      ajaxTimes++;
      wx.showLoading({
        title: '加载中',
        icon: 'loading',
        mask: true
      });

      var time = new Date().getTime();
      var string = this._baseUrl + "?apk_time=" + time + "&parameter=" + data.parameter;
      var smd5 = md5.md5(string).toLowerCase();
      data.apk_time = time;
      data.apk_data_md5 = smd5;
      //data.openid = openid;
      wx.request({
        url: this._baseUrl,
        //   method: method || METHOD.GET,
        method: "POST",
        data: {
          json: JSON.stringify(data),
          url: data.url,
        },
        header: {
          ...this._header,
        },
        success: res => {
          this.intercept(res) && resolve(res)
        },
        //   fail: reject,
        fail: function (res) {
          wx.showToast({
            title: '请求超时',
            icon: 'error'
          })
        },
        complete: function (res) {
          ajaxTimes--;
          if (ajaxTimes === 0) {
            wx.hideLoading()
          }
        },
      })

    })
  }

  uploadFile({
    data,
    file,
    bool
  }) {
    return new Promise((resolve, reject) => {
      ajaxTimes++;
      // console.log(ajaxTimes)
      wx.showLoading({
        title: '加载中',
        icon: 'loading',
        mask: true
      });

      var time = new Date().getTime();
      var string = this._baseUrl + "?apk_time=" + time + "&parameter=" + data.parameter;
      var smd5 = md5.md5(string).toLowerCase();
      data.apk_time = time;
      data.apk_data_md5 = smd5;

      wx.uploadFile({
        url: bool ? this._baseUrlFile2 : this._baseUrlFile, // 仅为示例，非真实的接口地址
        //   url: this._baseUrl,
        filePath: file,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data;'
        },
        formData: {
          json: JSON.stringify(data),
        },
        success: res => this.intercept(res) && resolve(res),
        fail: reject,
        complete: function (res) {
          console.log(res);
          ajaxTimes--;
          if (ajaxTimes === 0) {
            wx.hideLoading()
          }
        },
      });

    })
  }

  get(data) {
    return this.request({
      method: METHOD.GET,
      data
    })
  }
  post(data) {
    return this.request({
      method: METHOD.POST,
      data
    })
  }
  put(data) {
    return this.request({
      method: METHOD.PUT,
      data
    })
  }
  delete(data) {
    return this.request({
      method: METHOD.DELETE,
      data
    })
  }


  file(data, file, bool = false) {
    return this.uploadFile({
      data,
      file,
      bool
    })
  }

  // cookie(sessionid) {
  //   this._header.sessionid = wx.getStorageSync('userId')
  //   return this
  // }
  header(header) {
    this._header = header
    return this
  }
  // baseUrl(baseUrl) {
  //   this._baseUrl = "http://192.168.1.178:8080/"
  //   return this
  // }
  interceptor(f) {
    if (typeof f === 'function') {
      this.interceptors.push(f)
    }
    return this
  }







  // 判断权限
  /*  checkQx(qx){
       if(!loginOk){ this.getMyUser();return; }
       if(qx === "true"){return ;}
       if( role.indexOf(qx) == "-1" ){
           wx.showToast({ title: '用户无权限',icon:"error" });
           return false;
       }
       return true;
   } */
  // 自动登录
  autoLogin() {
    let that = this;
    wx.login({
      success(code) {
        var data = {
          parameter: "getOpenid",
          js_code: code.code,
        }
        that.get(data).then(res => {
          console.log("=======================================");
          console.log(res.data);
          openid = res.data.openid;
          if (res.data.iszc == "Y") {
            loginOk = true;
            userInfo = res.data;
            role = res.data.role.split(",");
          }
        }, (err) => {});
      }
    })
  }

  // 授权
  getMyUser() {
    let that = this;
    wx.getUserProfile({
      desc: "获取你的昵称、头像、地区及性别",
      success: res2 => {
        console.log(res2);
        wx.login({
          success(code) {
            console.log(code);
            var data = {
              parameter: "getOpenid",
              js_code: code.code,
            }
            that.get(data).then(res => {
              console.log(res);
              that.registerUser(res2.userInfo, res.data.openid);
              /* openid = res.data.openid; */
              /* if(res.data.iszc == "Y"){ 
                  loginOk = true; 
                  userInfo = res.data;
                  role = res.data.role.split(",");
              }
              else{ 
                  
              } */

            }, (err) => {
              wx.reLaunch({
                url: "/pages/index/index"
              });
              console.log(err);
            });
          }
        })
      },
      fail: res => {
        wx.reLaunch({
          url: "/pages/index/index"
        });
        console.log(res);
      }
    })
  }
  // 注册
  registerUser(info, openid) {
    var that = this;
    var data = {
      parameter: "login",
      openid: openid,
      nickname: escape(info.nickName),
      headimgurl: info.avatarUrl,
      sex: info.gender == 1 ? '1' : '0',
    }
    that.get(data).then(res => {
      if (res.data.code == "1000") {
        loginOk = true;
        userInfo = res.data;
        role = res.data.role.split(",");
        that.reloadPage();
      }
    }, (err) => {});
  }


  // 登录成功页面重载
  reloadPage() {
    let pages = getCurrentPages();
    let pageLen = pages.length - 1;
    let nowPage = pages[pageLen];
    let myquery = "";
    for (let key in nowPage.__displayReporter.query) {
      myquery += key + "=" + nowPage.__displayReporter.query[key] + "&"
    }
    wx.reLaunch({
      url: "/" + pages[pageLen].__route__ + (myquery ? "?" + myquery : "")
    });
  }
}
export default new Request
export {
  METHOD
}